import * as echarts from 'echarts';
import {LitElement, html, TemplateResult} from 'lit';
import {customElement, property} from "lit/decorators.js";
import style from '../echarts.css.ts';

export interface SankeyProps {
    chartId?: string;
    width?: string;
    height?: string;
    backgroundColor?: string;
    title?: object;
    tooltip?: object;
    data?: {name: string, itemStyle?: object}[];
    links?: {source: string, target: string, value: number}[];
    orient?: string;
    lineStyle?: object;
    itemStyle?: object;
}

@customElement('lit-sankey')
export class LitSankey extends LitElement {
    @property() chartId: string = 'sankey-chart';
    @property() width: string = '100%';
    @property() height: string = '100%';
    @property() backgroundColor: string = '#fff';
    @property() title: any = undefined;
    @property() tooltip: any = undefined;
    @property() data: {name: string}[] = [];
    @property() links: {source: string, target: string, value: number}[] = [];
    @property() orient: any = undefined;
    @property() lineStyle: any = {};
    @property() itemStyle: any = {};

    option: echarts.EChartsOption = {
        backgroundColor: this.backgroundColor,
        title: this.title,
        tooltip: this.tooltip,
        series: {
            type: 'sankey',
            emphasis: {
                focus: 'adjacency'
            },
            data: this.data,
            links: this.links,
            orient: this.orient,
            label: this.orient === 'vertical' ? {
                position: 'top',
            } : {},
            lineStyle: this.lineStyle || {},
            itemStyle: this.itemStyle || {},
        }
    };

    static styles = style;

    updated(): void {
        this.option.backgroundColor = this.backgroundColor;
        this.option.title = this.title;
        this.option.tooltip = this.tooltip;
        (this.option.series as any).data = this.data;
        (this.option.series as any).links = this.links;
        (this.option.series as any).orient = this.orient;
        (this.option.series as any).label = this.orient === 'vertical' ? {
            position: 'top',
        } : {};
        (this.option.series as any).lineStyle = this.lineStyle || {};
        (this.option.series as any).itemStyle = this.itemStyle || {};
        this.firstUpdated();
    }

    firstUpdated() {
        const chart = echarts.init(this.shadowRoot!.getElementById(this.chartId)!);
        chart.setOption(this.option);
    }

    render(): TemplateResult {
        return html`<div id="${this.chartId}" style="width:${this.width}; height:${this.height};"></div>`;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'lit-sankey': LitSankey;
    }
}